define [
  'backbone'
  'lib/ajax_setup'
], (Backbone, ajaxSetup) ->

  # Método onde é efetuado o override do Backbone.Sync especializado para a aplicação.
  Backbone.sync = (method, model, options) ->
    methodMap =
      'create' : 'POST',
      'update' : 'PUT',
      'delete' : 'DELETE',
      'read'   : 'GET'

    getValue = (object, prop) ->
      return null if !(object and object[prop])
      return if _.isFunction object[prop] then object[prop]() else object[prop]

    urlError = ->
      throw new Error 'A "url" property or function must be specified'

    type = methodMap[method]

    options or= {}

    params =
      type     : type,
      dataType : 'json',
      cache    : false,
      complete : ->
        $('#application-loading').remove()

    if !options.data and model and (method is 'create' or method is 'update')
      params.contentType = 'application/x-www-form-urlencoded'
      params.traditional = true
      params.data        = model.toJSON()

    if !options.url
      params.url = getValue(model, 'url') or urlError()
    if type is  'DELETE' or type is 'PUT'
      params.data or= {}
      params.data._method = type
      params.type = 'POST'
      params.beforeSend = (xhr) ->
        xhr.setRequestHeader 'X-HTTP-Method-Override', type

    promise = $.Deferred()

    ajaxPromise = $.ajax _.extend(params, options)
    ajaxPromise.error (error) ->
      ajaxSetup.error.apply @, arguments
      promise.reject.apply @, arguments

    ajaxPromise.done (json, status, ajaxObj) => promise.resolve.apply @, arguments

    promise